<template>
  <div class="admin-center">
    <el-container>
      <el-aside :width="isCollapse ? '64px' : '200px'" class="menu">
        <div class="logo" :class="{ 'logo-collapse': isCollapse }">
          <img src="@/assets/imgs/logo.png" alt="Logo" class="logo-img"/>
          <span v-show="!isCollapse" class="logo-text">天眼后台管理</span>
        </div>
        <el-menu
          :default-active="activeMenu"
          class="el-menu-vertical"
          :collapse="isCollapse"
          background-color="#304156"
          text-color="#bfcbd9"
          active-text-color="#409EFF"
        >
          <el-menu-item index="1" @click="handleSelect('1')">
            <el-icon><User /></el-icon>
            <template #title>用户管理</template>
          </el-menu-item>
          <el-menu-item index="2" @click="handleSelect('2')">
            <el-icon><Document /></el-icon>
            <template #title>帖子管理</template>
          </el-menu-item>
          <el-menu-item index="3" @click="handleSelect('3')">
            <el-icon><ChatLineRound /></el-icon>
            <template #title>评论管理</template>
          </el-menu-item>
          <el-menu-item index="4" @click="handleSelect('4')">
            <el-icon><Setting /></el-icon>
            <template #title>系统设置</template>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <el-container class="main-container">
        <el-header class="header">
          <div class="header-left">
            <el-icon 
              class="collapse-btn" 
              @click="toggleSidebar"
            >
              <Fold v-if="!isCollapse"/>
              <Expand v-else/>
            </el-icon>
            <breadcrumb class="breadcrumb" />
          </div>
          <div class="header-right">
            <el-dropdown trigger="click">
              <div class="admin-info">
                <el-avatar :size="32" :src="useUserStore().getUserInfo().avatar?useUserStore().getUserInfo().avatar:'https://tse2-mm.cn.bing.net/th/id/OIP-C.v3ywLkq_yuiisLQpDZ9wagHaGk?w=245&h=217&c=7&r=0&o=5&dpr=1.3&pid=1.7'" />
                <span class="admin-name">{{ userStore.getUserInfo().name }}</span>
                <el-icon><CaretBottom /></el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="showUserInfo">
                    <el-icon><User /></el-icon>个人信息
                  </el-dropdown-item>
                  <el-dropdown-item @click="showChangePassword">
                    <el-icon><Lock /></el-icon>修改密码
                  </el-dropdown-item>
                  <el-dropdown-item divided @click="handleLogout">
                    <el-icon><SwitchButton /></el-icon>退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>

        <el-main class="main">
          <transition name="fade-transform" mode="out-in">
            <component :is="currentComponent"></component>
          </transition>
        </el-main>
      </el-container>
    </el-container>
  </div>

  <!-- 添加对话框组件 -->
  <el-dialog
    v-model="userInfoDialogVisible"
    title="个人信息"
    width="400px"
    style="padding-right: 25px"
    @close="handleDialogClose"
  >
    <el-form :model="userInfo" label-width="80px">
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :http-request="handleAvatarUpload"
        >
          <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="账号">
        <el-input v-model="userInfo.username" disabled />
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="userInfo.name" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 100%" @click="handleSaveUserInfo">保存</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <el-dialog
    v-model="passwordDialogVisible"
    title="修改密码"
    width="400px"
  >
    <el-form
      :model="passwordForm"
      :rules="passwordRules"
      ref="passwordFormRef"
      label-width="100px"
    >
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="passwordForm.oldPassword" type="password" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="passwordForm.newPassword" type="password" show-password />
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleChangePassword">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineAsyncComponent, watch } from 'vue';
import { 
  User, 
  Document, 
  ChatLineRound, 
  Setting, 
  Fold, 
  Expand,
  CaretBottom,
  Lock,
  SwitchButton,
  Plus
} from '@element-plus/icons-vue';
import {useUserStore} from "@/stores/user";
import {ElMessageBox, ElMessage} from "element-plus";
import router from "@/router";
import {updateAvatarAPI, updatePasswordAPI, updateUserInfoAPI} from "@/apis/user";

// 动态导入组件
const UserManagement = defineAsyncComponent(() => import('./userManagement.vue'));
const PostManagement = defineAsyncComponent(() => import('./postManagement.vue'));
const CommentManagement = defineAsyncComponent(() => import('./commentManagement.vue'));
const SystemSettings = defineAsyncComponent(() => import('./systemSettings.vue'));

const isCollapse = ref(false);
const activeMenu = ref('1');
const currentComponent = ref(UserManagement);
const userStore=useUserStore()

const userInfoDialogVisible = ref(false);
const passwordDialogVisible = ref(false);
const userInfo = ref({
  username: useUserStore().getUserInfo().username,
  name: useUserStore().getUserInfo().name,
  avatar: useUserStore().getUserInfo().avatar
});

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

const passwordFormRef = ref();

const passwordRules = {
  oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 添加临时表单数据
const tempFormData = ref({
  file: null,
  avatar: '',
  name: ''
});

function handleSelect(key) {
  activeMenu.value = key;
  switch (key) {
    case '1':
      currentComponent.value = UserManagement;
      break;
    case '2':
      currentComponent.value = PostManagement;
      break;
    case '3':
      currentComponent.value = CommentManagement;
      break;
    case '4':
      currentComponent.value = SystemSettings;
      break;
  }
}

function toggleSidebar() {
  isCollapse.value = !isCollapse.value;
}

const handleLogout = () => {
  ElMessageBox.confirm('确认要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(()=>{
    userStore.clearUserInfo()
    router.push('/')
  })
}

const showUserInfo = () => {
  // userInfo.value = {
  //   username: props.initData.username || '',
  //   name: props.initData.name || '',
  //   avatar: props.initData.avatar || ''
  // }
  // tempFormData.value = {
  //   file: null,
  //   avatar: props.initData.avatar || '',
  //   name: props.initData.name || ''
  // }
  userInfoDialogVisible.value = true;
}

const showChangePassword = () => {
  passwordDialogVisible.value = true;
};

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
};

const handleAvatarUpload = async (options) => {
  // 只存储文件和临时显示，不立即上传
  tempFormData.value.file = options.file;
  // 创建临时URL用于预览
  userInfo.value.avatar = URL.createObjectURL(options.file);
};

const handleSaveUserInfo = async () => {
  try {
    // 如果有新的头像文件，先上传头像
    if (tempFormData.value.file) {
      const formData = new FormData();
      formData.append('uid', userStore.getUserInfo().uid);
      formData.append('file', tempFormData.value.file);
      const avatarRes = await updateAvatarAPI(formData);
      if (avatarRes.code !== '200') {
        ElMessage.error(avatarRes.msg || '头像上传失败');
        return;
      }
      userInfo.value.avatar = avatarRes.data;
    }

    // 更新用户信息
    const updateData = {
      ...userStore.getUserInfo(),
      name: userInfo.value.name,
      avatar: userInfo.value.avatar
    };
    
    const res = await updateUserInfoAPI(updateData);
    if (res.code === '200') {
      userStore.getUserInfo().name = updateData.name;
      userStore.getUserInfo().avatar = updateData.avatar;
      ElMessage.success('个人信息更新成功');
      userInfoDialogVisible.value = false;
    } else {
      ElMessage.error(res.msg || '更新失败');
    }
  } catch (error) {
    ElMessage.error('更新失败');
  }
};

const handleChangePassword = () => {
  passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      // TODO 修改密码
      const newUserInfo=useUserStore().getUserInfo()
      newUserInfo.password=passwordForm.value.oldPassword
      newUserInfo.newPassword=passwordForm.value.newPassword
      await updatePasswordAPI(JSON.stringify(newUserInfo)).then(res=>{
        if(res.code==='200'){
          ElMessage.success('密码修改成功，请重新登录')
          useUserStore().clearUserInfo()
          router.push('/login')
        }else{
          ElMessage.error(res.msg)
        }
      })
    }
  });
};

// 添加对话框关闭前的处理方法
const handleDialogClose = () => {
  // 重置表单数据
  userInfo.value = {
    username: userStore.getUserInfo().username,
    name: userStore.getUserInfo().name,
    avatar: userStore.getUserInfo().avatar
  };
  // 清理临时数据
  tempFormData.value = {
    file: null,
    avatar: '',
    name: ''
  };
  // 如果有创建的临时URL，需要释放
  if (userInfo.value.avatar && userInfo.value.avatar.startsWith('blob:')) {
    URL.revokeObjectURL(userInfo.value.avatar);
  }
};
</script>

<style scoped>
.admin-center {
  height: 100%;
  width: 100vw;
  overflow: hidden;
}

.el-container {
  height: 100%;
  width: 100%;
}

/* 修改 el-aside 的样式 */
:deep(.el-aside) {
  height: 100vh;
  overflow: hidden;
}

.menu {
  background-color: #304156;
  height: 100vh;
  transition: width 0.3s;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.logo {
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  background-color: #2b3648;
  overflow: hidden;
  transition: all 0.3s;
}

.logo-img {
  width: 32px;
  height: 32px;
  margin-right: 12px;
  transition: margin 0.3s;
}

.logo-collapse .logo-img {
  margin-right: 0;
}

.logo-text {
  color: #fff;
  font-size: 18px;
  font-weight: 600;
  white-space: nowrap;
  opacity: 1;
  transition: opacity 0.3s;
}

.el-menu {
  border-right: none;
  height: calc(100vh - 60px); /* 减去 logo 的高度 */
}

.el-menu-vertical:not(.el-menu--collapse) {
  width: 200px;
}

.main-container {
  //background-color: #f0f2f5;
}

.header {
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.collapse-btn {
  font-size: 20px;
  cursor: pointer;
  margin-right: 20px;
  transition: transform 0.3s;
}

.collapse-btn:hover {
  transform: scale(1.1);
}

.breadcrumb {
  margin-left: 8px;
}

.admin-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 0 8px;
  height: 40px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.admin-info:hover {
  background-color: rgba(0,0,0,.025);
}

.admin-name {
  margin: 0 8px;
  color: #333;
}

.main {
  padding: 20px;
  overflow-y: auto;
}

/* 过渡动画 */
.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: all 0.1s;
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(-30px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

/* 滚动条样式 */
.main::-webkit-scrollbar {
  width: 6px;
}

/* 菜单项样式 */
.el-menu-item {
  display: flex;
  align-items: center;
  transition: all 0.3s;
}

.el-menu-item:hover {
  background-color: #263445 !important;
}

.el-menu-item.is-active {
  background-color: #1890ff !important;
  color: #fff !important;
}

:deep(.el-menu-item.is-active) {
  color: #fff !important;
}

:deep(.el-menu-item:hover) {
  color: #fff !important;
}

/* 下拉菜单样式 */
:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-dropdown-menu__item:not(.is-disabled):hover) {
  background-color: #f5f7fa;
}

.avatar-uploader {
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
}

.avatar-uploader-icon:hover {
  border-color: #409EFF;
}
</style>
